package com.sdy.hospitalguard.web.interceptor;

import com.sdy.common.model.Response;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.config.SdyMvcConfig;
import com.sdy.mvc.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Value("${res.app.noAuthentiation:/static,/favicon.ico,/opt/file/healthcode}")
    private String noAuthentiation;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 过滤静态资源
        if (ignoreResource(request, noAuthentiation)) {
            return true;
        }
        Integer userId = (Integer) request.getSession().getAttribute(com.sdy.common.constant.Constants.SESSION_USER_ID);
        if (userId == null) {
            return reject(response, null, Response.Code.noAuthentication);
        }
        // 已登录
        return true;
    }

    private boolean ignoreResource(ServletRequest servletRequest, String ignorePath) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String currentUrl = request.getRequestURI();
        // 过滤静态资源
        if (StringUtil.isNotBlank(ignorePath)) {
            String[] noAuthentiationUrls = ignorePath.split(",");
            for (String noAuthentiationUrl : noAuthentiationUrls) {
                if (currentUrl.startsWith(noAuthentiationUrl)) {
                    return true;
                }
            }
        }
        // 过滤druid
        if (currentUrl.startsWith("/druid")) {
            return true;
        }
        // 过滤服务调用API
        if (SdyMvcConfig.isServiceCall(request)) {
            return true;
        }
        return false;
    }

    private boolean reject(HttpServletResponse response, String errorInfo, Integer errorCode) throws IOException {
        String respJson = JsonUtil.toJson(Response.error(errorInfo, errorCode));
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(respJson == null ? "" : respJson);
        response.getWriter().flush();
        response.getWriter().close();
        return false;
    }
}
